import { get, post, put, request, downloadFile, exportExcel } from './api';
import { ApiResponse, TaskReportListResponse, TaskReport } from '../pages/ai_reports/models/aiReportsModels';
import axios from 'axios';

/**
 * 获取任务报告列表
 * @returns 任务报告列表数据
 */
export const getTaskReportList = (): Promise<ApiResponse<TaskReportListResponse>> => {
  return get<ApiResponse<TaskReportListResponse>>('/taskreport');
};

/**
 * 更新任务报告
 * @param id 任务报告ID
 * @param data 更新的任务报告数据
 * @returns 更新结果
 */
export const updateTaskReport = (id: number, data: Partial<TaskReport>): Promise<ApiResponse<TaskReport>> => {
  return put<ApiResponse<TaskReport>>(`/taskreport/${id}`, data);
};

/**
 * 导出任务报告为Excel
 * @returns 导出操作的Promise
 */
export const exportTaskReportExcel = (): Promise<void> => {
  return exportExcel('/taskreport/exportexcel', undefined, '任务报告');
};

/**
 * 生成周报明细
 * @returns 生成结果
 */
export const generateWeeklyReportDetail = (): Promise<ApiResponse<any>> => {
  return get('/taskreport/genreports');
};

/**
 * 生成周报HTML
 * @returns 生成的HTML内容
 */
export const generateWeeklyReportHtml = (): Promise<ApiResponse<string>> => {
  return post('/taskreport/generatehtml');
};

/**
 * 下载HTML文件
 * @param htmlContent HTML内容
 * @param filename 文件名（不含扩展名）
 */
export const downloadHtmlFile = (htmlContent: string, filename: string = 'report'): void => {
  // 创建Blob对象
  const blob = new Blob([htmlContent], { type: 'text/html;charset=utf-8' });
  
  // 创建URL
  const url = URL.createObjectURL(blob);
  
  // 创建下载链接
  const link = document.createElement('a');
  link.href = url;
  
  // 添加日期到文件名
  const date = new Date();
  const dateStr = date.getFullYear().toString() +
                 (date.getMonth() + 1).toString().padStart(2, '0') +
                 date.getDate().toString().padStart(2, '0');
  
  link.download = `${filename}_${dateStr}.html`;
  
  // 触发下载
  document.body.appendChild(link);
  link.click();
  
  // 清理
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
};

/**
 * 保存HTML到服务器
 * @param htmlContent HTML内容
 * @returns 保存结果
 */
export const saveHtmlToServer = (htmlContent: string): Promise<ApiResponse<any>> => {
  return post('/taskreport/savehtml', { htmlContent });
};

